package com.qf.servlet;

import org.apache.commons.io.IOUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.UUID;

/**
 * @author Ypl
 * @version V1.0
 * @Project September-mavens
 * @Package com.qf.servlet
 * @Description:
 * @Date 2022/10/8 19:27
 */
@SuppressWarnings("all")
@Controller
public class TestServlet {

    /**
     * 上传，从本地上传到服务器
     */

    @RequestMapping("/upload")
    @ResponseBody
    public void upload(String username, MultipartFile file, HttpSession session){
//        接受前端传来的参数
//        文件名，随机的
        String s = UUID.randomUUID().toString();

//        获取原始文件名
        String filename = file.getOriginalFilename();
        String[] split = filename.split("[.]");

//        获取后缀名,下表永远为最后一个的
        String s1 = split[split.length - 1];
//        要上传的文件名
        String upName = s + "." +s1;
        //动态获取路径
        String realPath = session.getServletContext().getRealPath("/img");
        File file1 = new File(realPath);
        //判断路径，如果不存在就创建一个
        if(!file1.exists()){
            file1.mkdirs();
        }
        try {
            file.transferTo(new File(file1,upName));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 下载，从服务器下载到本地
     */
    @RequestMapping("/download")
    @ResponseBody
    public void  download(String name, HttpServletResponse response) throws  Exception{
        response.setHeader("content-disposition", "attachment;filename="+name);
        IOUtils.copy(new FileInputStream("D:\\图片\\湖人.jpg"),response.getOutputStream());
    }
}
